import React , { Component } from 'react';
import PropTypes from 'proptypes';
import Comments from '../../components/comments';
import { createComments, fetchThread, fetchComments } from '../../actions';
import { connect } from 'react-redux';
import style from './index.css';

class Thread extends Component {
    componentWillMount () {
        this.props.fetchThread(this.props.params.id);
        this.props.fetchComments(this.props.params.id);
    }
    render () {
        const { comments, title, content, createComments } = this.props
        const id = this.props.params.id;
        return (
            <div className={style.container}>
                <h1>{ title }</h1>
                <div className={style.left}>
                    <article className={style.content}> {content} </article>
                    <div>
                        {
                            comments.map((c, index) => <Comments {...c} key={index}/> )
                        }
                    </div>
                </div>
                <div className={style.rightcontrol}>
                    <div className={style.commentcreator}>
                        <textarea className={style.commentInput} cols="30" id="" name="" rows="10" ref="input" placeholder="input your idea"></textarea>
                        <button className={style.commentSend} onClick={() => createComments(id, this.refs.input.value)}>send</button>
                    </div>
                </div>
            </div>
        )
    }
}

Thread.defaultProps = {
    comments: []
}
Thread.propTypes = {
    title: PropTypes.string,
    content: PropTypes.string,
    uuid: PropTypes.string,
    comments: PropTypes.arrayOf(PropTypes.shape({
        content: PropTypes.string,
        username: PropTypes.string
    }))
}

function mapStateToProps (state) {
    return {
        ...state.thread.resources,
        comments: state.comment.resources[state.thread.resources && state.thread.resources.uuid]
    }
}
function mapDispatchToProps (dispatch) {
    return {
        createComments: (id, content) => dispatch(createComments(id, content)),
        fetchThread: id => dispatch(fetchThread(id)),
        fetchComments: id => dispatch(fetchComments(id))
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Thread)
